<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller {  
  
  public function index()
  {
    // Redirect to dashboard if user already logged in
    if ($this->session->userdata('login')) redirect('dashboard');
    
    if ($this->input->post('email') != '' || $this->input->post('password') != '')
    {
      $email    = $this->input->post('email');
      $password = $this->input->post('password');
      
      $this->load->model('guests_model');
      
      if ($this->guests_model->validate_password($email, $password))
        $this->create_session($email);
      else
        $this->session->set_flashdata('alert', 'login');
    }
    
    $data['page_title'] = title('Login');
    $data['alert']      = alerts();
    
    $this->load->helper('form');
    
    $this->load->view('templates/header', $data);
    $this->load->view('login/login_view', $data);
    $this->load->view('templates/footer', $data);
  }
  
  // ===========================================================================
  
  public function register()
  { 
    // Redirect to dashboard if user already logged in
    if ($this->session->userdata('login')) redirect('dashboard');
    
    // display page based on uri
    // http://prop.ashish.co/register/2
    switch($this->uri->segment(2))
    {
      // Display the main register page
      case 1:
      case '':
        $data['page_title']    = title('Register');
        $data['register_page'] = 1;
        
        $this->load->view('templates/header', $data);
        $this->load->view('login/register', $data);
        $this->load->view('templates/footer', $data);
        
        break;
      
      // Allow user to enter email and add group members
      case 2:
        $data['page_title']    = title('Register: Step 2');
        $data['register_page'] = 2;
        $data['type']          = $this->input->get('ticket');
        
        $this->load->helper('form');
        
        $this->load->view('templates/header', $data);
        $this->load->view('login/register', $data);
        $this->load->view('templates/footer', $data);
        
        break;
      
      // Verify email address and create user accounts in database
      case 3:
        
        $emails = $this->input->post('email');
        
        $data['is_camping'] = $this->input->post('ticket') == 'camping' ? TRUE : FALSE;
        
        $this->load->model('guests_model');
        
        // Create record for person registering
        $data['name']     = $this->input->post('name');
        $data['email']    = $emails[1];
        $data['group_id'] = $this->guests_model->get_new_group();
        
        $code = $this->guests_model->register($data);
        $this->send_verification_email($data['email'], $code);
        
        // Remove the person registering from the array
        unset($data['name']);
        unset($emails[1]);
        
        // Create record for everyone else
        foreach ($emails as $email)
        {
          if ($email != '')
          {
            $data['email'] = $email;
            $code = $this->guests_model->register($data);
          
            $this->send_verification_email($email, $code);
          }
        }
        
        echo "Please click on verification link in your email.";
        
        break;
      
      // Complete registraion and login
      case 4:
      case 'code':

        // Process if user submits the form
        if ($this->input->post('password') != '')
        {
          $email              = $this->input->post('email');
          $data['password']   = $this->input->post('password');
          $data['dob']        = $this->input->post('dob');
          $data['address_1']  = $this->input->post('add1');
          $data['address_2']  = $this->input->post('add2');
          $data['city']       = $this->input->post('city');
          $data['state']      = $this->input->post('state');
          $data['country']    = $this->input->post('country');
          $data['zip']        = $this->input->post('zip');
          $data['created_at'] = date('Y-m-d H-i-s');
          
          if ($this->input->post('name') != '')
            $data['name'] = $this->input->post('name');
          
          $this->load->model('guests_model');
          
          $this->guests_model->update_user($data, $email);
          $this->guests_model->update_password($data['password'], $email);
          
          $this->create_session($email);
        }
        
        // http://prop.ashish.co/register/code/abcd1234
        $code = $this->uri->segment(3);
        
        if ($code == '') exit('Invalid Reset Code');
        
        $this->load->model('guests_model');
        
        $email = $this->guests_model->get_reset_email($code);
        
        if ($email != '')
        {
          $data['page_title']    = title('Register: Step 4');
          $data['email']         = $email;
          $data['register_page'] = 4;
          $data['name']          = $this->guests_model->get_user_data('name', $email) == '' ? TRUE : FALSE;
          
          $this->load->helper('form');
          
          $this->load->view('templates/header', $data);
          $this->load->view('login/register', $data);
          $this->load->view('templates/footer', $data);
        }
        else
          exit('Invalid Reset Code');
        
        break;
      
      // if user navigates to uri other than the ones above
      default:
        redirect();
    }
  }
  
  // ===========================================================================
  
  public function logout()
  {
    // Destory the CodeIgniter session cookie
    $this->session->sess_destroy();
    
    redirect('login');
  }
  
  // =============================================================================
  
  private function send_verification_email($email, $code)
  {
    $from     = $this->session->userdata('email');
    $subject  = 'STUNE: Verify Email';
    $link     = site_url('register/code/' . $code);
    $message  = 'Please click this link to complete your registration: ' . $link;
    
    $this->load->library('email');
    
    $config['wordwrap'] = FALSE;

    $this->email->initialize($config);
    
    $this->email->from('stune@ashish.co', 'STUNE');
    $this->email->to($email);
    $this->email->subject($subject);
    $this->email->message($message);
    
    $this->email->send();
  }
  
  // ===========================================================================
  
  private function create_session($email)
  {
    // Set CodeIgniter's cookie based session
    $this->session->sess_create();
        
    $session = array(
      'email'     => $email,
      'user_id'   => $this->guests_model->get_user_data('guest_id', $email),
      'login'     => TRUE
    );
    
    // add custom session data
    $this->session->set_userdata($session);
    
    redirect('dashboard');
  }
}

// End of File